<?php
class Helper_BSS_NCA
{
	var $controller_dir;
	
	function getAllActions($controller_dir = '')
	{
		if ($controller_dir)
		{
			$this->controller_dir = $controller_dir;
		}
		else
		{
			$this->controller_dir = Q::ini('app_config/APP_DIR') . '/controller/';
		}
		$ctrl_file = array_flip(self::findControllerFiles($this->controller_dir));
		return $this->findActionsInFiles($ctrl_file);
	}
	
	private function findControllerFiles($dir)
	{
		$handle = opendir($dir);
		$ctrl_files = array();
		while ($file = readdir($handle))
		{
			$filename = $dir . '/' . $file;
			if ($file != '.' && $file != '..' && filetype($filename) == 'dir')
			{
				$sub_dir_files = Helper_BSS_NCA::findControllerFiles($filename);
				$ctrl_files = array_merge($ctrl_files, $sub_dir_files);
			}
			elseif ($file != '.' && $file != '..' && substr(strtolower($file), -15) == '_controller.php')
			{
				$ctrl_files[] = substr(str_replace($this->controller_dir, '', $dir . '/' . $file), 1);;
			}
		}
		closedir($handle);
		return $ctrl_files;
	}
	
	private function findActionsInFiles($ctrl_files)
	{
		$class_pattern = '/class\sController_(.+?)\sextends/i';
		$function_pattern = '/function\saction(.+?)\(.+?\{(.+?)\}/';
		$title_pattern = '/_view\[\'title\'\]\s=\s\'(.+?)\'/';
		$nca = array();
		foreach ($ctrl_files as $filename => $val)
		{
			$file_content = php_strip_whitespace($this->controller_dir . $filename);
			preg_match_all($class_pattern, $file_content, $class_matched);
			if(isset($class_matched[1][0]))
			{
				if (stripos($filename, '/'))
				{
					$namespace_controller = explode('_', $class_matched[1][0]);
					$namespace_name = strtolower($namespace_controller[0]);
					$controller_name = strtolower($namespace_controller[1]);
				}
				elseif (stripos($class_matched[1][0] , '_'))
				{
					$namespace_controller = explode('_', $class_matched[1][0]);
					$namespace_name = strtolower($namespace_controller[0]);
					$controller_name = strtolower($namespace_controller[1]);
				}
				else
				{
					$namespace_name = 'default';
					$controller_name = strtolower($class_matched[1][0]);
				}
				preg_match_all($function_pattern, $file_content, $function_matched);
				if(isset($function_matched[1]))
				{
					foreach ($function_matched[1] as $key => $action)
					{
						$action_name = strtolower($action);
						preg_match_all($title_pattern, $function_matched[2][$key], $title_matched);
						$desc = empty($title_matched[1]) ? '' : $title_matched[1][0];
						$nca[$namespace_name . '_' . $controller_name . '_' . $action_name] = array(
							'namespace' => $namespace_name,
							'controller' => $controller_name,
							'action' => $action_name,
							'desc' => $desc
						);
					}
				}
			}
		}
		return $nca;
	}
}